package org.ourgrid.broker.business.schedulerdata.executor;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.business.dao.BrokerDAOFactory;
import org.ourgrid.broker.business.dao.PeerEntry;
import org.ourgrid.broker.business.dao.WorkerDAO;
import org.ourgrid.broker.business.schedulerdata.SchedulerData;
import org.ourgrid.broker.response.DisposeWorkerResponseTO;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.response.ReleaseResponseTO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DisposeWorkerExecutor extends AbstractSchedulerDataExecutor {
	
	/**
	 * <DISPOSE_WORKER peerID='String' workerID='String'/>
	 */
	public List<IResponseTO> execute(SchedulerData command) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		Document logDocFile = super.getXMl(command.getXml());
		
		Element element = logDocFile.getDocumentElement();
		
		String pID = element.getAttribute("peerID");
		String wID = element.getAttribute("workerID");
		
		if (pID != null && wID != null) {
			PeerEntry peerEntry = BrokerDAOFactory.getInstance().getPeerDAO().getPeerEntry(getAddress(pID));
			
			DisposeWorkerResponseTO disposeTO = new DisposeWorkerResponseTO();
			disposeTO.setPeerAddress(peerEntry.getPeerSpec().getServiceID().toString());
			
			WorkerDAO workerDAO = BrokerDAOFactory.getInstance().getWorkerDAO();
			
			String workerAddress = getAddress(wID);
			
			disposeTO.setWorkerAddress(workerAddress);
			disposeTO.setWorkerPublicKey(workerDAO.getWorkerPublicKey(workerAddress));
			
			responses.add(disposeTO);
			
			ReleaseResponseTO releaseTO = new ReleaseResponseTO();
			releaseTO.setStubAddress(workerAddress);
			
			responses.add(releaseTO);
			
			workerDAO.removeWorker(workerAddress);
		}	
		
		return responses;
	}
}
